import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Plus,
  Edit,
  Trash2,
  Search,
  MoreHorizontal,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { positionDutyAPI } from "@/api/PositionDuty";

// 生成时间戳ID（精确到毫秒）
const generateTimestampId = () => {
  return Date.now().toString(); // 转换为字符串，避免大数字精度问题
};

// 表单组件：新增/编辑职位职责
const PositionDutyForm = ({
  isEditing,
  initialData,
  onSubmit,
  onCancel,
  isLoading,
}) => {
  const [formData, setFormData] = useState({
    duty: initialData?.duty || "",
    position: initialData?.position || "",
    id: initialData?.id || "", // 编辑时使用已有ID，新增时后续自动生成
  });

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.duty.trim()) {
      alert("工作职责不能为空");
      return;
    }
    if (!formData.position.trim()) {
      alert("职业不能为空");
      return;
    }
    // 新增时自动生成时间戳ID，编辑时使用原有ID
    const submitData = isEditing
      ? formData
      : { ...formData, id: generateTimestampId() };
    await onSubmit(submitData);
  };

  return (
    <Card className="shadow-md rounded-lg border border-gray-100 overflow-hidden">
      <CardHeader className="bg-gray-50 border-b border-gray-100">
        <CardTitle className="flex items-center gap-2 text-lg font-medium text-gray-800">
          <Plus className="w-5 h-5 text-blue-500" />
          {isEditing ? "编辑职位职责" : "新增职位职责"}
        </CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-5">
          <div className="space-y-2">
            <Label
              htmlFor="position"
              className="text-sm font-medium text-gray-700"
            >
              职业 <span className="text-red-500">*</span>
            </Label>
            <Input
              id="position"
              name="position"
              value={formData.position}
              onChange={handleInputChange}
              placeholder="例如：材料管理员"
              disabled={isLoading}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="duty" className="text-sm font-medium text-gray-700">
              职责描述 <span className="text-red-500">*</span>
            </Label>
            <Input
              id="duty"
              name="duty"
              value={formData.duty}
              onChange={handleInputChange}
              placeholder="例如：负责项目材料采购"
              disabled={isLoading}
            />
          </div>
          <div className="flex justify-end gap-3 pt-2">
            <Button
              type="button"
              variant="ghost"
              onClick={onCancel}
              disabled={isLoading}
              className="h-10 px-4 text-gray-600 hover:bg-gray-100 hover:text-gray-800"
            >
              取消
            </Button>
            <Button
              type="submit"
              disabled={isLoading}
              className="h-10 px-6 bg-blue-600 hover:bg-blue-700 text-white"
            >
              {isLoading ? "提交中..." : "确认提交"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
};

export default function PositionDutyManager() {
  const [duties, setDuties] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);

  // 计算总页数
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  
  // 计算当前页需要显示的数据（修复分页的核心逻辑）
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentDuties = duties.slice(indexOfFirstItem, indexOfLastItem);

  // 加载数据列表（带分页支持）
  const fetchData = async () => {
    setIsLoading(true);
    try {
      // 这里假设API支持分页参数，如果后端不支持分页，可去掉参数只获取全部数据
      const res = await positionDutyAPI.getList({
        page: currentPage,
        pageSize: itemsPerPage
      });
      
      // 格式化数据，确保每条数据有ID
      const formattedData = (res.data?.list || res.data || []).map((item) => ({
        ...item,
        id: item.id || generateTimestampId(),  
      }));
      
      setDuties(formattedData);
      // 设置总条数（如果后端返回total则用后端数据，否则用实际数据长度）
      setTotalItems(res.data?.total || formattedData.length);
    } catch (error) {
      console.error("加载职位职责列表失败:", error);
      alert("加载职位职责列表失败，请稍后重试");
    }
    setIsLoading(false);
  };

  // 当页码或每页条数变化时重新加载数据
  useEffect(() => {
    fetchData();
  }, [currentPage, itemsPerPage]);

  // 分页变更处理
  const handlePageChange = (page) => {
    if (page < 1 || page > totalPages) return;
    setCurrentPage(page);
  };

  // 每页条数变更处理
  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 重置到第一页
  };

  // 新增
  const handleAdd = async (formData) => {
    setIsLoading(true);
    try {
      // 确保新增数据的ID是时间戳
      const newData = { ...formData, id: generateTimestampId() };
      await positionDutyAPI.create(newData);

      // 刷新数据
      await fetchData(); 
      setShowForm(false);
      setEditingId(null);
    } catch (error) {
      console.error("新增职位职责失败:", error);
      alert(`新增失败: ${error.response?.data?.message || "系统错误"}`);
    }
    setIsLoading(false);
  };

  // 编辑
  const handleEdit = async (formData) => {
    setIsLoading(true);
    try {
      await positionDutyAPI.update(formData.id, formData);
      // 刷新数据
      await fetchData(); 
      setShowForm(false);
      setEditingId(null);
    } catch (error) {
      console.error("更新职位职责失败:", error);
      alert(`更新失败: ${error.response?.data?.message || "系统错误"}`);
    }
    setIsLoading(false);
  };

  // 删除
  const handleDelete = async (id) => {
    if (!window.confirm("确定要删除该职位职责吗？")) return;
    setIsLoading(true);
    try {
      await positionDutyAPI.delete(id);
      // 刷新数据
      await fetchData(); 
    } catch (error) {
      console.error("删除职位职责失败:", error);
      alert("删除职位职责失败，请稍后重试");
    }
    setIsLoading(false);
  };

  // 渲染分页组件
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1 || isLoading}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
                disabled={isLoading}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages || isLoading}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  return (
    <Card className="shadow-sm">
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2"> 
          职位职责管理
        </CardTitle>
        <Button
          onClick={() => {
            setShowForm(true);
            setEditingId(null);
          }}
          size="sm"
          disabled={isLoading}
        >
          <Plus className="w-4 h-4 mr-1" /> 新增
        </Button>
      </CardHeader>
      <CardContent>
        {showForm && (
          <PositionDutyForm
            isEditing={!!editingId}
            initialData={duties.find((item) => item.id === editingId) || {}}
            onSubmit={editingId ? handleEdit : handleAdd}
            onCancel={() => {
              setShowForm(false);
              setEditingId(null);
            }}
            isLoading={isLoading}
          />
        )}

        {isLoading ? (
          <div className="flex justify-center items-center py-12">
            <svg
              className="animate-spin -ml-1 mr-3 h-8 w-8 text-blue-600"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              ></circle>
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              ></path>
            </svg>
          </div>
        ) : duties.length === 0 ? (
          <div className="text-center py-12 text-gray-500">
            <MoreHorizontal className="w-12 h-12 mx-auto mb-3 opacity-40" />
            <h4 className="text-base font-medium mb-1">暂无职位职责数据</h4>
            <p className="text-sm max-w-md mx-auto">
              点击"新增"按钮创建职位职责信息
            </p>
          </div>
        ) : (
          <>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>职业</TableHead>
                  <TableHead>职责描述</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {/* 使用当前页数据渲染表格（关键修复点） */}
                {currentDuties.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>{item.position}</TableCell>
                    <TableCell>{item.duty}</TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-8 w-8 p-0"
                          >
                            <MoreHorizontal className="w-4 h-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem
                            onClick={() => {
                              setShowForm(true);
                              setEditingId(item.id);
                            }}
                          >
                            <Edit className="w-4 h-4 mr-2" /> 编辑
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => handleDelete(item.id)}
                            className="text-red-600"
                          >
                            <Trash2 className="w-4 h-4 mr-2" /> 删除
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            {renderPagination()}
          </>
        )}
      </CardContent>
    </Card>
  );
}